package cn.wlinker.driver.bacnet;

import cn.hutool.core.bean.BeanUtil;
import cn.wlinker.driver.bacnet.domain.BacnetBaseBean;
import cn.wlinker.driver.bacnet.domain.BacnetLocalDeviceBean;
import cn.wlinker.driver.bacnet.domain.BacnetObject;
import cn.wlinker.driver.bacnet.utils.BacnetLocalDeviceHelper;
import cn.wlinker.driver.bacnet.utils.BacnetReadHandler;
import cn.wlinker.driver.bacnet.utils.BacnetWriteHandler;
import cn.wlinker.driver.common.AbstractDriver;
import lombok.SneakyThrows;

import java.util.List;
import java.util.Map;

/**
 * bacnet 驱动
 *
 * @author gxsjx
 * @version 1.0
 * @date 2022/9/17
 * Copyright © wlinker.cn
 */
public class BacnetDriver extends AbstractDriver<BacnetLocalDeviceBean, BacnetBaseBean, BacnetObject> {

    private static final BacnetObject NULL_OBJ = new BacnetObject();

    @Override
    protected String getConnectionKey() {
        return connectionMap.get("localBindAddress").toString();
    }

    public BacnetDriver(Map<String, Object> connectionMap) {
        super(connectionMap);
    }

    @Override
    public BacnetLocalDeviceBean getConnectionBean() {
        return BeanUtil.toBean(connectionMap, BacnetLocalDeviceBean.class);
    }

    @Override
    public Boolean open() throws Exception {
        return BacnetLocalDeviceHelper.connect(getConnectionBean());
    }

    @SneakyThrows
    @Override
    public Boolean isOpen() {
        return BacnetLocalDeviceHelper.isOpen(getConnectionBean());
    }

    @Override
    public List<BacnetObject> discovery() {
        return BacnetReadHandler.discoveryDeviceForList(getConnectionBean());
    }

    @Override
    public BacnetObject read(BacnetBaseBean dto) {
        return BacnetReadHandler.read(getConnectionBean(), dto).orElse(NULL_OBJ);
    }

    @Override
    public Boolean write(BacnetBaseBean dto) {
        return BacnetWriteHandler.write(getConnectionBean(),dto);
    }

    @Override
    public Boolean close() {
        return BacnetLocalDeviceHelper.close(getConnectionBean());
    }
}
